<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\PublicCommentController;
use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaDepartment;
use app\model\WaMembers;
use app\model\WaMonthlySettlement;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\controller\wmapi\IndexController;
use app\model\WaOrdersPurchaseAmountDetail;
use app\model\WaOrdersPurchaseContract;
use app\model\WaOrdersRelevance;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaOrdersSalesAmountDetail;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaProducts;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchasedVehiclesAmountDetail;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaSupplier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;
use function Symfony\Component\String\s;

class MonthlySettlementController extends Validate
{

    /**
     **************************************************** 款项 ****************************************************
     */

    /**
     * 转月结
     * 所有月结的 款项都在对应订单的  amount_detil 详情数据里
     * 这边是 供应商 月份的汇总订单(用于列表生成 请款单)
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $module_type = 0;// 模块类型 1 采购模块 2 车辆管理模块
        $where_monthly_settlement = [];

        // 款项名称
        if (!array_key_exists('price_name', $param)) {
            return IndexController::errored('', '款项名称,必传');
        }else{
            $price_name = $param['price_name'];
        }

        // 款项名称
        if (!array_key_exists('total_price', $param)) {
            return IndexController::errored('', '款项金额,必传');
        }


        if ($param['supplier_type']  && $param['supplier_id']){

            $supplier = IndexController::supplierDetailCommon($param['supplier_type'],$param['supplier_id']);
            if (!$supplier) {
                return IndexController::errored($supplier, '供应商详情获取失败');
            }
            $supplier = json_decode($supplier);

            $supplier_id = $param['supplier_id'];
            $supplier_type = $param['supplier_type'];
            $supplier_name = $supplier->name;

        }else{
            return IndexController::errored('', '缺少必要入参-> 供应商 type / id');
        }

        // 获取车辆明细详情信息
        $wpvad_condition = [];
        $wpvad_condition [] = ['id', '=', $param['amount_id']];
        $wpvad_find = WaPurchasedVehiclesAmountDetail::find($wpvad_condition);

        if (!$wpvad_find){
            return IndexController::errored('', '获取车辆明细详情信息失败');
        }
        $wpvad_find = json_decode($wpvad_find);

        // 获取车辆信息
        $wpv_condition = [];
        $wpv_condition [] = ['vin', '=', $wpvad_find->vin];
        $wpv_find = WaPurchasedVehicles::find($wpv_condition);
        $wpv_find = json_decode($wpv_find);
        if (!$wpv_find){
            return IndexController::errored('', '获取车辆信息失败');
        }


        if ($wpvad_find->payment_type == 2){
            return IndexController::errored('', '已转为月结无需重复操作');
        }

        // 获取当前月的第一天的开始时间
        $first_day_of_month = strtotime("first day of this month 00:00:00");
        // 获取当前月的最后一天的结束时间
        $last_day_of_month = strtotime("last day of this month 23:59:59");
        $data = [
            'vin' => $wpvad_find->vin,
            'supplier_type' => intval($supplier_type), // 供应商类型： 1车辆供应商 2上牌供应商 3 国际货运代理 4保险供应商 5 国内物流
            'supplier_id' => intval($supplier_id),
            'supplier_name' => $supplier_name, // 供应商名称
            'price_name' => $price_name, // 款项类目名称(购置税，上牌费用等)
            'amount_id' => $param['amount_id'],
            'created_at' => dateTime(),
            'settlement_sratus' => 1, // 结算状态 1 待结算 2 请款中 3 已结算 4 删除
//            'approve_stauts' => 0, // 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
            'admin_id' => $adminId->id,
            'admin_name' => $adminId->nickname,
            'total_price' => $param['total_price'],
            'module_type' => $module_type,
            'bill_number' => 'Y'.date('Y', time()).'M'.date('m', time()).'Sid'.$supplier_id.'Ty'.$supplier_type,
            'year' => date('Y', time()),
            'month' => date('m', time()),
            'first_day_of_month' => $first_day_of_month,
            'last_day_of_month' => $last_day_of_month,
            'purchase_order_sn' => $wpv_find->purchase_order_sn,
            'purchase_order_sn_child' => $wpv_find->purchase_children_sn,


        ];
        $data['year_month'] = $data['year'].'/'.$data['month']; // 供应商月份年份类型拼接


        //修改 选中的月结订单 结算状态为 请款中  修改审批状态为审批中(自动提交审批)

        // 判断款项是已存在
        $where_monthly_settlement [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
        $where_monthly_settlement [] = ['supplier_type', '=', intval($supplier_type)];
        $where_monthly_settlement [] = ['supplier_id', '=', intval($supplier_id)];
        $where_monthly_settlement [] = ['price_name', '=', $price_name];
        $where_monthly_settlement [] = ['settlement_sratus', '<=', 3]; // 结算状态 1 待结算 2 已结算 4 删除
        $monthly_settlement = WaMonthlySettlement::find($where_monthly_settlement);
        $monthly_settlement = json_decode($monthly_settlement);
        if ($monthly_settlement) {
            return IndexController::errored('', '该笔款项已存在');
        }

        \support\Db::beginTransaction();
        try {

            $result  = WaMonthlySettlement::created($data);
            if (!$result){
                return IndexController::errored('', '月结款项单创建失败');
            }

            // 更新 车辆明细 支付方式  和 账单号
            $condition_vehicles_detail_up = [];
            $condition_vehicles_detail_up [] = ['id', '=', $param['amount_id']]; // 车辆明细id
            $condition_vehicles_detail_data = [
                'payment_type' => 2, // 支付方式  1 现结 2 月结
                'bill_number' => $data['bill_number'], // 月结账单编号
                'updated_at' => dateTime(),
            ];
            $wpvad_up = WaPurchasedVehiclesAmountDetail::updated($condition_vehicles_detail_data,$condition_vehicles_detail_up);
            if (!$wpvad_up){
                return IndexController::errored('', '车辆明细信息更新失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '月结款项单创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('monthlySettlementCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '月结款项单创建失败');
        }

    }

    /**
     * 月结款项-撤回
     * 审批中 和 审批通过的 不能撤回 数据 溯源问题
     * 撤回会删除(软删)当前款项  对应订单的额 款项状态会变回 待请款
     * 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
     * 结算状态 1 待结算 2 请款中 3 已结算 4 撤回(即删除 订单中的状态需求变回待请款)
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementWithdraw(Request $request)
    {
        $param = $request->all();
        $monthly_settlement_find_condition = [];
        $monthly_settlement_find_condition [] = ['id', '=', $param['monthly_settlement_id']];
        $res = WaMonthlySettlement::find($monthly_settlement_find_condition);
        if ($res) {
            $res = json_decode($res);

            // 查询审批中是否有 审批中 或 审批通过的记录
            $payroll_requisition_condition = [];
            $payroll_requisition_condition [] = ['bill_number','=',$res->bill_number];
            $payroll_requisition_data = WaPurchasePayrollRequisition::find($payroll_requisition_condition);
            $payroll_requisition_data = json_decode($payroll_requisition_data);
            if ($payroll_requisition_data){
//                if (in_array($payroll_requisition_data->status,[1,2,3])){
//                    return IndexController::errored('', '请款记录中有 审批中 或 审批通过的状态不能撤回');
//                }
                if ($payroll_requisition_data->status > 0){
                    return IndexController::errored('', '已请款状态下，单项撤回只有 待审批状态 可以撤回');
                }
            }
            // 修改车辆费用明细状态为现结
            $monthly_settlement_all_condition = [];
            $monthly_settlement_all_condition [] = ['id', '=', $param['monthly_settlement_id']];
            $res_all = WaMonthlySettlement::find($monthly_settlement_all_condition);
            $res_all = json_decode($res_all);
            if ($res_all){
                // 修改对应订单的 款项的是否月结状态为否 is_monthly_settlement    是否月结 1 否 2 是
                $amount_is_monthly_settlement = [
                    'payment_type' => 1, // 支付方式  1 现结 2 月结
                    'bill_number' => '', //
                    'updated_at' => dateTime(),
                ];
                $amount_is_monthly_settlement_condition = [];
                $amount_is_monthly_settlement_condition [] = ['id', '=', $res_all->amount_id];
                WaPurchasedVehiclesAmountDetail::updated($amount_is_monthly_settlement,$amount_is_monthly_settlement_condition);

            }



//            // 撤回(软删)当前款项记录
//            $monthly_settlement_data = [
//                'settlement_sratus' => 4, // 结算状态 1 待结算 2 请款中 3 已结算 4 撤回(即删除 订单中的状态需求变回待请款)
//                'updated_at' => dateTime(),
//            ];
//            $monthly_settlement_condition = [];
//            $monthly_settlement_condition [] = ['id', '=', $param['monthly_settlement_id']];
//            $month_up = WaMonthlySettlement::updated($monthly_settlement_data,$monthly_settlement_condition);
//            if (!$month_up){
//                return IndexController::errored('', '月结状态更新失败');
//            }

            // 撤回 删除月结记录 太多会造成数据筛选混乱

            $monthly_settlement_del_condition = [];
            $monthly_settlement_del_condition [] = ['id', '=', $param['monthly_settlement_id']];
            $month_up = WaMonthlySettlement::deleted($monthly_settlement_del_condition);
            if (!$month_up){
                return IndexController::errored('', '月结记录删除失败');
            }




        }else{
            return IndexController::errored('', '月结款项撤回失败');

        }


        return IndexController::successed('', '撤回成功');

    }

    /**
     * 月结请款单-所有款项撤回
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementWithdrawAll(Request $request)
    {
        $param = $request->all();
        $monthly_settlement_find_condition = [];
        $monthly_settlement_find_condition [] = ['bill_number', '=', $param['bill_number']];
        $res = WaMonthlySettlement::find($monthly_settlement_find_condition);
        $res = json_decode($res);
        if ($res) {
            PublicCommentController::月结订单结算状态;
            PublicCommentController::请款单状态;
            if ($res->settlement_sratus != 1){
                return IndexController::errored('', '只有审批中的月结订单可以撤回');
            }
            // 查询审批中是否有 审批中 或 审批通过的记录
            $payroll_requisition_condition = [];
            $payroll_requisition_condition [] = ['purchase_payroll_sn','=',$res->purchase_payroll_sn];
            $payroll_requisition_data = WaPurchasePayrollRequisition::find($payroll_requisition_condition);
            $payroll_requisition_data = json_decode($payroll_requisition_data);
            if ($payroll_requisition_data){
                if (!in_array($payroll_requisition_data->status,[1,4])){
                    return IndexController::errored('', '请款单已请款状态下,只有 待审批状态 或 审核不通过转态可以撤回');
                }
            }
            PublicCommentController::请款单状态;
            $payroll_data = [
                'status' => 5,
                'updated_at' => dateTime(),
            ];
            $payroll_requisition_up = WaPurchasePayrollRequisition::updated($payroll_data, $payroll_requisition_condition);
            if (!$payroll_requisition_up){
                return IndexController::errored('', '月结请款单撤回状态修改失败');
            }


            // 修改车辆费用明细状态为现结
            $monthly_settlement_all_condition = [];
            $monthly_settlement_all_condition [] = ['bill_number', '=', $param['bill_number']];
            $res_all = WaMonthlySettlement::all($monthly_settlement_all_condition);
            $res_all = json_decode($res_all);

            if ($res_all) {
                foreach ($res_all as $kll){
                    // 修改对应订单的 款项的是否月结状态为否 is_monthly_settlement    是否月结 1 否 2 是
                    $amount_is_monthly_settlement = [
                        'payment_type' => 1, // 是否月结 1 否 2 是
                        'bill_number' => '', //
                        'updated_at' => dateTime(),
                    ];

                    $amount_is_monthly_settlement_condition = [];
                    $amount_is_monthly_settlement_condition [] = ['id','=', $kll->amount_id];
                    WaPurchasedVehiclesAmountDetail::updated($amount_is_monthly_settlement,$amount_is_monthly_settlement_condition);
                }
            }


//            // 撤回(软删)当前款项记录
//            $monthly_settlement_data = [
//                'settlement_sratus' => 4, // 结算状态 1 待结算 2 请款中 3 已结算 4 撤回(即删除 订单中的状态需求变回待请款)
//                'updated_at' => dateTime(),
//            ];
//            $monthly_settlement_condition = [];
//            $monthly_settlement_condition [] = ['bill_number', '=', $param['bill_number']];
//            $month_up = WaMonthlySettlement::updated($monthly_settlement_data,$monthly_settlement_condition);
//            if (!$month_up){
//                return IndexController::errored('', '月结状态更新失败');
//            }


            // 撤回 删除月结记录 太多会造成数据筛选混乱

            $monthly_settlement_del_condition = [];
            $monthly_settlement_del_condition [] = ['bill_number', '=', $param['bill_number']];
            $month_up = WaMonthlySettlement::deleted($monthly_settlement_del_condition);
            if (!$month_up){
                return IndexController::errored('', '月结记录删除失败');
            }








        }else{
            return IndexController::errored('', '月结款项撤回失败');

        }


        return IndexController::successed('', '撤回成功');

    }




    /**
     **************************************************** 账单 ****************************************************
     */

    /**
     * 月结账单列表
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementList(Request $request)
    {
//        process($request);
        $param = $request->all();

        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        $condition = [];
        $between = [];

        if (array_key_exists('supplier_type', $param)){
            if ($param['supplier_type']) {
                $condition [] = ['supplier_type', '=', $param['supplier_type']];
            }
        }

        if (array_key_exists('supplier_name', $param)){
            if ($param['supplier_name']) {
                $condition [] = ['supplier_name', 'like', '%' . $param['supplier_name'] . '%'];
            }
        }

        if (array_key_exists('settlement_sratus', $param)){
            if ($param['settlement_sratus']) {
                $condition [] = ['settlement_sratus', '=', $param['settlement_sratus']];
            }
        }

        if (array_key_exists('bill_number', $param)){
            if ($param['bill_number']) {
                $condition [] = ['bill_number', '=', $param['bill_number']];
            }
        }



        $condition [] = ['settlement_sratus', '!=', 4];


        if (array_key_exists('start_time', $param) && array_key_exists('end_time', $param)){
            if ($param['start_time'] && $param['end_time']) {
                $start_time = strtotime($param['start_time']);
                $end_time = strtotime($param['end_time']) + (60*60*24);
                $condition [] = ['first_day_of_month', '>=', $start_time];
                $condition [] = ['last_day_of_month', '<=', $end_time];
//                $between [] = [$start_time, $end_time];
            }
        }

        $fields = ['*'];
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $listOrder = WaMonthlySettlement::list($page, $pageNum, $fields,  $condition, $between);
        return IndexController::successed($listOrder, '月结账单列表');

    }

    /**
     * 月结账单详情
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementDetail(Request $request)
    {
        $param = $request->all();
        $condition = [];
        $condition [] = ['bill_number', '=', $param['bill_number']];
        $condition [] = ['settlement_sratus', '!=', 4];
        $res = WaMonthlySettlement::all($condition);


        return IndexController::successed($res, '月结账单详情');

    }



    /**
     **************************************************** 请款 ****************************************************
     */

    /**
     * 月结付款列表
     * @param Request $request
     * @return Response
     */
    public function monthlySettlementPayrollRequisitionList(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        $condition = [];
        $between = [];

        if ($param['admin_name']) {
            $condition [] = ['admin_name', 'like', '%' . $param['admin_name'] . '%'];
        }

        if ($param['supplier_type']) {
            $condition [] = ['supplier_type', 'like', '%' . $param['supplier_type'] . '%'];
        }

        if ($param['status'] || $param['status'] == 0) {
            $condition [] = ['status', '=', $param['status']];
        }

        if ($param['bill_number']) {
            $condition [] = ['bill_number', '=', $param['bill_number']];
        }
        PublicCommentController::请款单请款结算类型;
        $condition [] = ['payroll_requisition_type', '=', 3]; // 请款类型
        $condition [] = ['status', '!=', 5]; //  0待审批 1审批中 2 待付款 3 已付款 4 审核不通过 5 撤回 6 删除


        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $whereIn = [];
        if(in_array($adminId->department_id,[44,45])){ // 采购部 国际物流部
            $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
            $whereIn = $next_epartment_members;
        }


        $fields = ['*'];
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $listOrder = WaPurchasePayrollRequisition::list($adminId,$page, $pageNum, $whereIn, $fields, $condition, $between);
        return IndexController::successed($listOrder, '月结请款单列表');

    }




}